<template>
  <div class="edit-article-container">
    <el-form ref="formRef" :model="form" :rules="formRule" label-position="top">
      <el-form-item prop="title" label="文章标题">
        <el-input v-model="form.title" placeholder="请输入文章标题" />
      </el-form-item>

      <el-form-item prop="editorText" label="文章内容">
        <Editor
          ref="editorRef"
          :initialValue="form.editorText"
          height="600px"
          @blur="handleEditorBlur"
          :options="editorOptions"
        />
        <div class="el-form-item__error" v-show="showError">请输入文章内容</div>
      </el-form-item>

      <el-form-item prop="description" label="文章描述">
        <el-input
          v-model="form.description"
          placeholder="请输入文章描述"
          type="textarea"
          :rows="5"
        />
      </el-form-item>

      <el-form-item label="文章头图">
        <Upload v-model="form.thumb" />
      </el-form-item>

      <el-form-item prop="categoryId" label="文章分类">
        <el-select v-model="form.categoryId" @change="handleCategoryChange">
          <el-option
            v-for="item in blogTypes"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-button
        type="primary"
        style="margin-top: 15px"
        @click="handlePulishArticle"
        >{{ mode === "edit" ? "确认修改" : "发布文章" }}</el-button
      >
    </el-form>
  </div>
</template>

<script>
import { Editor } from "@toast-ui/vue-editor";
import "@toast-ui/editor/dist/toastui-editor.css";
import Upload from "@/components/Upload";
import { getBlogType } from "@/api/blogType";
import { addBlog, findOneBlog, editBlog } from "@/api/blog";
import "@toast-ui/editor/dist/i18n/zh-cn";

export default {
  name: "EditArticle",
  props: ["mode"],
  components: { Editor, Upload },
  data() {
    return {
      form: {
        title: "",
        editorText: "",
        description: "",
        thumb: "",
        categoryId: "",
      },
      formRule: {
        title: [{ required: true, message: "请输入文章名称", trigger: "blur" }],
        description: [
          { required: true, message: "请输入文章描述", trigger: "blur" },
        ],
        categoryId: [
          { required: true, message: "请选择文章分类", trigger: "change" },
        ],
      },
      blogTypes: [],
      showError: false,
      editorOptions: {
        language: "zh-CN",
      },
    };
  },
  created() {
    this.fetchBlogType();
    if (this.mode === "edit") {
      this.id = this.$route.params.id;
      this.fetchBlogDetail();
    }
  },
  methods: {
    fetchBlogDetail() {
      findOneBlog(this.id).then(({ data }) => {
        this.form = { ...data };
        this.form.categoryId = data.category.id;
        this.form.select = data.category === null ? "" : data.category.id;
        this.$refs.editorRef.invoke("setHTML", data.htmlContent);
      });
    },
    fetchBlogType() {
      getBlogType().then((res) => {
        this.blogTypes = res.data;
      });
    },
    handlePulishArticle() {
      this.handleEditorBlur();
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          const htmlContent = this.$refs.editorRef.invoke("getHTML");
          const markdownContent = this.$refs.editorRef.invoke("getMarkdown");
          const body = {
            ...this.form,
            htmlContent,
            markdownContent,
            toc: [],
            createDate: new Date().getTime(),
          };
          if (this.mode === "edit") {
            editBlog(body).then(() => {
              this.$message.success("修改文章成功");
              this.$router.push("/blogList");
            });
          } else {
            addBlog(body).then(() => {
              this.$message.success("发布文章成功");
              this.$router.push("/blogList");
            });
          }
        }
      });
    },
    handleEditorBlur() {
      const content = this.$refs.editorRef.invoke("getMarkdown");
      const domEl = document.querySelector(".toastui-editor-defaultUI");
      if (!content) {
        this.showError = true;
        domEl.style.borderColor = "#F56C6C";
      } else {
        this.showError = false;
        domEl.style.borderColor = "#dadde6";
      }
    },
    handleCategoryChange() {
      this.$forceUpdate();
    },
  },
};
</script>

<style scoped lang="scss">
.edit-article-container {
  padding: 20px;
  .block {
    margin: 15px 0;
    font-weight: 100;
  }
}
</style>
